import { Button, Input, Select, Divider, TreeSelect, message, Popconfirm, Tag } from 'antd';
import React, { useState, useRef } from 'react';
import { useRequest } from 'umi';
import { PaginationProps } from 'antd/lib/pagination';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { PageContainer } from '@ant-design/pro-layout';
import { PlusOutlined } from '@ant-design/icons';

import CreateForm from '@/components/CreateForm';
import { api } from '@/services/config';
import { UserItem, RoleItem, TreeNodeItem, SearchParam } from '../data';
import { handleUser, getUsers, resetPassword } from '../service';
import { getQuertParam, exportExcel } from '@/utils/utils';

const User: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [total, setTotal] = useState<number>();
  const [pagination, setPagination] = useState<PaginationProps>({});
  const [selectRecord, handleSelectRecord] = useState<UserItem | undefined>(undefined);
  const [modalVisible, handleModalVisible] = useState<boolean>(false);

  const [searchParam, setSearchParams] = useState<SearchParam>({});

  const defualtPwd = 'HRisk@2021';

  const { data: roleRes } = useRequest(api.system.getRoles);

  const convertRoleData = (): TreeNodeItem[] => {
    const roleList = roleRes || [];
    const treeNodes: TreeNodeItem[] = [];
    roleList.forEach((ele: RoleItem) => {
      treeNodes.push({
        value: `${ele.id}`,
        title: `${ele.description}`,
      });
    });
    return treeNodes;
  };

  const columns: ProColumns<UserItem>[] = [
    {
      title: '序号',
      width: 50,
      align: 'center',
      dataIndex: 'index',
      valueType: 'index',
      render: (text, record, index) => {
        const { current = 1, pageSize = 10 } = pagination;
        return (current - 1) * pageSize + index + 1;
      },
    },
    {
      title: '姓名',
      width: 50,
      align: 'center',
      dataIndex: 'userName',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入姓名',
          },
        ],
      },
      renderFormItem: (item, { type, defaultRender, ...rest }) => {
        if (type === 'form') {
          return <Input {...rest} placeholder="请输入姓名" />;
        }
        return defaultRender(item);
      },
    },
    {
      title: '登录名',
      width: 100,
      align: 'center',
      dataIndex: 'loginName',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入登录名',
          },
        ],
      },
      renderFormItem: (item, { type, defaultRender, ...rest }) => {
        if (type === 'form') {
          return <Input {...rest} placeholder="请输入登录名" />;
        }
        return defaultRender(item);
      },
    },
    {
      title: '性别',
      dataIndex: 'sex',
      hideInSearch: true,
      align: 'center',
      width: 50,
      render: (text) => {
        if (text === 1) {
          return '男';
        }
        if (text === 2) {
          return '女';
        }
        return '-';
      },
      renderFormItem: (item, { type, defaultRender, ...rest }) => {
        if (type === 'form') {
          return (
            <Select {...rest} placeholder="请选择性别" allowClear>
              <Select.Option value={1}>男</Select.Option>
              <Select.Option value={2}>女</Select.Option>
            </Select>
          );
        }
        return defaultRender(item);
      },
    },
    {
      title: '手机号',
      width: 100,
      align: 'center',
      hideInSearch: true,
      dataIndex: 'phone',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            // required: true,
            message: '请输入手机号',
          },
        ],
      },
      renderFormItem: (item, { type, defaultRender, ...rest }) => {
        if (type === 'form') {
          return <Input {...rest} placeholder="请输入手机号" />;
        }
        return defaultRender(item);
      },
    },
    {
      title: '用户角色',
      width: 100,
      align: 'center',
      hideInSearch: true,
      dataIndex: 'roles',
      valueType: 'text',
      render: (_, record) => {
        let rolesArr = record.roles;
        if (rolesArr.length > 0) {
          return rolesArr.map((item: RoleItem) => <Tag color="blue">{item.description}</Tag>);
        } else {
          return '-';
        }
      },
      renderFormItem: (item, { type, defaultRender, ...rest }) => {
        if (type === 'form') {
          return (
            <TreeSelect
              // {...rest} 去掉此行，解决不能同时显示
              placeholder="请为用户分配角色"
              allowClear
              showSearch
              style={{ width: '100%' }}
              dropdownStyle={{ overflow: 'auto' }}
              treeData={convertRoleData()}
              treeCheckable
              treeCheckStrictly
            />
          );
        }
        return defaultRender(item);
      },
    },
    {
      title: '操作',
      width: 80,
      align: 'center',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handleModalVisible(true);
              handleSelectRecord(record);
            }}
          >
            修改
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title="确定删除?"
            onConfirm={() => {
              handleUser({ method: 'DELETE', id: record.id }).then(({ code, msg }) => {
                if (code === 0) {
                  message.success('删除成功！');
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                } else {
                  message.error('删除失败！');
                }
              });
            }}
            okText="是"
            cancelText="否"
            placement="left"
          >
            <a href="#">删除</a>
          </Popconfirm>
          <Divider type="vertical" />
          <Popconfirm
            title="确定重置密码?"
            onConfirm={() => {
              resetPassword({ id: record.id }).then(({ code, msg }) => {
                if (code === 0) {
                  message.success('重置密码成功，默认密码：' + defualtPwd);
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                } else {
                  message.error('重置密码失败，请稍后重试！');
                }
              });
            }}
            okText="是"
            cancelText="否"
            placement="left"
          >
            <a href="#">重置密码</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  /**
   * 导出
   * @param form
   */
  const handleExport = (form: any) => {
    // let params = '';
    // const values = form.getFieldsValue();
    // Object.keys(values).forEach((key) => {
    //   params += `&${key}=${values[key] || ''}`;
    // });

    // 此方式会打开一个新页面，下载后关掉，方式不好，使用如下封装的a链接的方式
    // window.open(`/api/user/download?${params}`);

    const url =
      '/api/user/download?current=' +
      searchParam.current +
      '&pageSize=' +
      searchParam.pageSize +
      '&order=' +
      searchParam.order +
      '&sortParam=' +
      searchParam.sortParam +
      '&param=' +
      JSON.stringify(searchParam.param);

    // 导出
    exportExcel(url);
  };

  return (
    <PageContainer title={false}>
      <ProTable<UserItem>
        rowKey="id"
        bordered
        columns={columns}
        actionRef={actionRef}
        pagination={{
          total,
          pageSize: 10,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              handleModalVisible(true);
              handleSelectRecord(undefined);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={(params) => {
          const { current, pageSize, ...data } = params;
          const paramsT = {
            current,
            pageSize,
            order: true,
            sortParam: 'id',
            param: getQuertParam(data),
          };
          //保存查询参数,导出使用
          setSearchParams(paramsT);
          return getUsers(paramsT); // 单独处理查询请求，因为里面含有特殊参数param,含大括号，自动转义
        }}
        postData={(data: any) => {
          setTotal(data.total);
          return data.records || [];
        }}
        search={{
          optionRender: ({ searchText, resetText }, { form }) => [
            <Button
              key="search"
              type="primary"
              onClick={() => {
                form?.submit();
              }}
            >
              {searchText}
            </Button>,
            <Button
              key="rest"
              onClick={() => {
                form?.resetFields();
              }}
            >
              {resetText}
            </Button>,
            <Button key="out" onClick={() => handleExport(form)}>
              导出
            </Button>,
          ],
        }}
      />

      <CreateForm
        modalVisible={modalVisible}
        title={selectRecord ? '修改用户' : '新增用户'}
        onCancel={() => {
          handleModalVisible(false);
          handleSelectRecord(undefined);
        }}
      >
        <ProTable<UserItem, UserItem>
          rowKey="id"
          type="form"
          columns={columns}
          form={{
            labelCol: { span: 4 },
            wrapperCol: { span: 20 },
            initialValues: {
              ...selectRecord,
              password: undefined,
              // roles: selectRecord?.roles?.split(','),
              roles: selectRecord?.roles?.map((item: RoleItem) => {
                return item.id + ''; //必须是字符串类型
              }),
            },
          }}
          onSubmit={async (value) => {
            let roleIds = [];
            if (value.roles) {
              roleIds = value.roles.map((x: any) => {
                return { id: x.value };
              });
              delete value.roles.value;
            }
            const values = {
              method: selectRecord ? 'PUT' : 'POST',
              ...selectRecord,
              ...value,
              roles: roleIds,
            };
            const { code, msg } = await handleUser(values);
            if (code === 0) {
              message.success(
                selectRecord ? '修改用户成功' : '新建用户成功，默认密码：' + defualtPwd,
              );
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            } else {
              message.error(msg);
            }
          }}
        />
      </CreateForm>
    </PageContainer>
  );
};

export default User;
